<template>
  <div v-loading="loading">
    <table class="table table-bordered vertical-align-middle text-center approve-table">
      <colgroup>
        <col width="15%" />
        <col width="30%" />
        <col width="15%" />
        <col width="40%" />
      </colgroup>

      <tr>
        <td>反担保方式</td>
        <td colspan="3" class="text-left">
          <ul class="list-inline">
            <li class="list-inline-item mr-5" v-for="(guad, index) in guadTypes" :key="index">
              <checked-box :value="guad.value"></checked-box>
              <span>{{ guad.label }}</span>
            </li>
          </ul>
        </td>
      </tr>
      <tr>
        <td>反担保措施</td>
        <td colspan="3" class="text-left">
          <div v-html="guaMethodHtml"></div>
        </td>
      </tr>
      <tr>
        <td>业务合同类型</td>
        <td colspan="3">
          <ul class="list-unstyled text-left">
            <li v-for="(bc, index) in busContracts" :key="index" class="d-flex align-items-center">
              <checked-box :value="bc.value" style="min-width: 16px"></checked-box>
              <div class="ml-3" style="min-width: 180px">{{ bc.label }}</div>
              <div v-if="bc.showNum">
                <div style="min-width: 180px" v-if="isView">{{ bc.num }}份</div>
                <el-input
                  v-model="bc.num"
                  class="my-1"
                  size="mini"
                  style="width: 130px"
                  v-input-number="{ min: 0, fixed: 0 }"
                  @blur="setValue(bc)"
                  v-else
                >
                  <span slot="append">份</span>
                </el-input>
              </div>
              <div v-if="bc.attachKey">
                <template v-if="isView">
                  <div
                    v-for="file in areadyFiles[bc.attachKey]"
                    :key="file.url"
                    class="file-item bg-light my-1 px-2"
                  >
                    <attach-item :attach-data="file"></attach-item>
                    <!-- <small>
                      {{ file.name }}
                      <el-button type="text" @click="handleDownloadFile(file)">下载</el-button>
                    </small> -->
                  </div>
                </template>
                <div v-else class="d-flex align-items-center">
                  <div class="mr-3">
                    <input
                      type="file"
                      :ref="`up-${bc.attachKey}`"
                      class="d-none"
                      multiple
                      accept="*"
                      @change="e => handleFileChange(e, bc.attachKey)"
                    />
                    <el-button
                      plain
                      size="mini"
                      class="ml-3"
                      icon="el-icon-upload2"
                      :disabled="saveLoading"
                      @click="e => handleSelectFile(`up-${bc.attachKey}`)"
                    >
                      上传
                    </el-button>
                  </div>
                  <div class="flex-1 p-2 rounded">
                    <div
                      v-for="(file, i) in areadyFiles[bc.attachKey]"
                      :key="file.url"
                      class="file-item bg-light my-1 px-2"
                    >
                      <div class="d-flex">
                        <attach-item :attach-data="file"></attach-item>
                        <el-button
                          class="text-danger"
                          type="text"
                          :disabled="saveLoading"
                          @click="handleDeleteFile(1, i, bc.attachKey)"
                        >
                          删除
                        </el-button>
                      </div>
                    </div>
                    <div
                      v-for="(file, index) in attachs[bc.attachKey]"
                      :key="index"
                      class="file-item bg-light my-1 px-2"
                    >
                      <small>
                        {{ file.name }}
                        <el-button
                          type="text"
                          class="text-danger"
                          :disabled="saveLoading"
                          @click="handleDeleteFile(2, index, bc.attachKey)"
                        >
                          删除
                        </el-button>
                      </small>
                    </div>
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </td>
      </tr>
    </table>

    <approve-common
      v-bind="$attrs"
      :view-mode="viewMode"
      :related-data="relatedData"
      :approve-data="approveData"
      :before-save="submit"
      @success="handleSuccess"
    ></approve-common>
    <!-- <el-button @click="submit">提交</el-button> -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getContractData,
  updateContract,
  addContract,
} from '@/credit/views/county/unionProvince/components/contractApproveDeploy/index'
import { uploadOss, deleteOss } from '@/common/api/oss'
import { arrayFromString, arrayToString } from '@vimi/utils-tool'
import { fileAdapter, attachAdapter } from '@/bank/components/attach/index'
import { revokeObjectURL } from '@/common/plugins/tools/file'
import { exportUrl } from '@/common/api/download'
import ApproveCommon from '@/credit/views/county/unionProvince/components/contractApproveDeploy/ApproveCommon'
import { formatLine } from '@/common/plugins/tools/format'
import AttachItem from '@/bank/components/attach/Item'
export default {
  components: {
    ApproveCommon,
    AttachItem,
    'checked-box': {
      props: {
        value: Boolean,
      },
      render(h) {
        const { value } = this
        return h(
          'span',
          {
            style: {
              display: 'inline-block',
              verticalAlign: 'middle',
              borderWidth: '1px',
              borderStyle: 'solid',
              borderColor: value ? 'var(--primary)' : '#333',
              color: value ? 'var(--primary)' : '',
              width: '16px',
              height: '16px',
              lineHeight: '16px',
              textAlign: 'center',
              borderRadius: '2px',
              marginRight: '0.5rem',
            },
          },
          value ? [h('span', {}, '√')] : ''
        )
      },
    },
  },
  props: {
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    approveData: {
      type: Object,
      default: () => ({
        editable: false,
        record: [],
      }),
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      busContracts: [],
      loadVarieties: 1,
      saveLoading: false,
      uploadFiles: [],
      attachs: {
        entrust_attachment: [],
        gua_ensure_attachment: [],
        gua_pledge_attachment: [],
        gua_mortgage_attachment: [],
        bank_gua_attachment: [],
        other_attachment: [],
      },
      areadyFiles: {
        entrust_attachment: [],
        gua_ensure_attachment: [],
        gua_pledge_attachment: [],
        gua_mortgage_attachment: [],
        bank_gua_attachment: [],
        other_attachment: [],
      },
      deleteFiles: [],
      contractData: {},
    }
  },

  created() {},
  computed: {
    ...mapGetters(['entrustContract', 'guardDatas']),
    queryId() {
      return this.relatedData.customer_related_id
    },
    // 合同审批表
    approvalId() {
      return this.contractData.contract_approval_id
    },
    isView() {
      // return false
      return this.viewMode || !this.approveData.editable
    },
    guaMethodHtml() {
      return formatLine(this.entrustContract.gua_method_des || this.contractData.gua_des)
    },
    // 反担保方式
    guadTypes() {
      const res = [
        { label: '保证', type: 1, value: false },
        { label: '质押', type: 2, value: false },
        { label: '抵押', type: 3, value: false },
        { label: '其他', type: 55, value: false },
        { label: '无（信用）', type: 66, value: false },
      ]
      this.busContracts.map(guad => {
        const r = res.find(it => it.type && it.type === +guad.type)
        if (r) {
          r.value = guad.value
        }
      })
      this.$emit('get-type', { type: 'guadTypes', data: res })
      return res
    },
    // 反担保措施拼接
    // guardCombines() {
    //   const enumCombineFn = {
    //     1: this.getGuadGuarantee,
    //     2: this.getGuadPledge,
    //     3: this.getGuadMortgage,
    //   }
    //   return this.guardDatas
    //     .filter(it => [1, 2, 3].includes(+it.gua_method))
    //     .map(it => ({
    //       id: it.gua_contract_id,
    //       combineStr: enumCombineFn[it.gua_method](it),
    //     }))
    // },
  },
  watch: {
    entrustContract: {
      handler: function (val) {
        this.loadVarieties = +val.loan_varieties || 1
      },
      immediate: true,
      deep: true,
    },
    guardDatas: {
      handler: function () {
        this.busContracts = this.getBusContracts()
      },
      immediate: true,
      deep: true,
    },
    queryId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  methods: {
    async submit() {
      const data = {
        customer_related_id: this.queryId,
        res_a_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'), // 合同完成时间
        // 保存数量
        ...this.busContracts.reduce((prev, curr) => {
          prev[curr.key] = curr.num || 0
          return prev
        }, {}),
        // gua_des: this.guardCombines
        //   .map((item, index) => `${index + 1}、${item.combineStr}`)
        //   .join(','),
        gua_des: this.entrustContract.gua_method_des,
      }
      await this.deleteOssFiles()
      for (let key of Object.keys(this.attachs)) {
        const uploadData = {}
        uploadData[key] = this.attachs[key].map(it =>
          uploadOss({
            file: it.file,
            dir: `credit/contract/approve/${this.queryId}`,
            type: 0,
            progress: ({ percent }) => {
              it.percent = percent
              it.loading = percent < 100
            },
          })
        )
        data[key] = await Promise.all(uploadData[key])
          .then(list => {
            return arrayToString([...this.areadyFiles[key].map(it => it.url), ...list])
          })
          .catch(err => {
            this.$message.error(err?.errorMessage ?? '上传失败')
          })
      }
      return this.updataApproval(data)
    },
    deleteOssFiles() {
      if (!this.deleteFiles.length) return Promise.resolve()
      const attachs = this.guardDatas.filter(
        item => +item.gua_method === 1 && +item.gua_entity_type === 1
      )
      const attachment = []
      attachs.forEach(item => {
        attachment.push(...arrayFromString(item.attachment))
      })
      // 删除时候过滤掉反担保合同附件
      return deleteOss(
        this.deleteFiles.filter(item => !attachment.includes(item.url)).map(it => it.url)
      )
    },
    updataApproval(data) {
      // 修改
      if (this.approvalId) {
        return updateContract(this.approvalId, data)
      }

      // 添加
      return addContract({
        ...data,
        service_id: this.relatedData.service_id,
        recommend_service: this.relatedData.recommend_service,
      })
    },
    handleSuccess(res) {
      this.$emit('success', res)
    },
    getData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      getContractData(this.queryId)
        .then(res => {
          this.contractData = res
          this.busContracts = this.getBusContracts()
          this.initForm(res)
        })
        .finally(() => {
          this.loading = false
        })
    },
    initForm(data) {
      Object.keys(this.areadyFiles).forEach(key => {
        const item = arrayFromString(data[key])
        this.areadyFiles[key] = item.reduce((prev, curr) => {
          prev.push(
            attachAdapter({
              attachment: curr,
            })
          )
          return prev
        }, [])
      })
      // 第一次审批，将反担保合同法人的附件同步过来
      const startApprove = this.approveData?.record?.[0] ?? {}
      if (
        this.approveData.record &&
        this.approveData.record.length === 1 &&
        startApprove.editable
      ) {
        const attachs = this.guardDatas.filter(
          item => +item.gua_method === 1 && +item.gua_entity_type === 1
        )

        attachs.forEach(item => {
          arrayFromString(item.attachment).map(url => {
            this.areadyFiles['other_attachment']?.push(
              attachAdapter({
                attachment: url,
              })
            )
          })
        })
      }
    },
    handleDownloadFile(attach) {
      const { url, name } = attach
      exportUrl({
        url,
        filename: name,
      })
    },
    handleDeleteFile(type, index, key) {
      if (type === 2) {
        const file = this.attachs[key][index]
        revokeObjectURL(file.url)
        this.attachs[key].splice(index, 1)
      } else {
        this.deleteFiles.push(...this.areadyFiles[key].splice(index, 1))
      }
    },
    handleSelectFile(upkey) {
      const uploadInput = this.$refs[upkey]
      uploadInput[0].click()
    },

    handleFileChange(e, key) {
      const { files = [] } = e.target
      if (!this.attachs[key]) {
        this.attachs[key] = []
      }
      for (let i = 0; i < files.length; i++) {
        this.attachs[key].push(fileAdapter(files[i]))
      }
      this.resetInput(key)
    },
    resetInput(key) {
      const uploadInput = this.$refs[`up-${key}`]
      if (uploadInput) {
        uploadInput[0].value = ''
      }
    },
    setValue(bc) {
      bc.value = +bc.num > 0
      this.busContracts[6].value = !this.busContracts.some(
        (item, index) => +item.num > 0 && index > 0 && index < 6
      )
    },
    // 业务合同类型
    getBusContracts() {
      const res = [
        {
          label: '委托担保合同',
          value: true,
          num: 1,
          showNum: true,
          key: 'entrust_contract_amount',
          attachKey: 'entrust_attachment',
        },
        {
          label: '反担保保证合同',
          type: 1,
          value: false,
          num: 0,
          showNum: true,
          key: 'gua_ensure_amount',
          attachKey: 'gua_ensure_attachment',
        },
        {
          label: '反担保质押合同',
          type: 2,
          value: false,
          num: 0,
          showNum: true,
          key: 'gua_pledge_amount',
          attachKey: 'gua_pledge_attachment',
        },
        {
          label: '反担保抵押合同',
          type: 3,
          value: false,
          num: 0,
          showNum: true,
          key: 'gua_mortgage_amount',
          attachKey: 'gua_mortgage_attachment',
        },
        {
          label: '银担保证合同',
          value: false,
          num: 0,
          showNum: true,
          key: 'bank_gua_amount',
          attachKey: 'bank_gua_attachment',
        },
        {
          label: '其他',
          type: 55,
          value: false,
          num: 0,
          showNum: true,
          key: 'other_amount',
          attachKey: 'other_attachment',
        },
        {
          label: '无（信用）',
          type: 66,
          value: false,
          num: 0,
          showNum: false,
          key: 'nothing_amount',
        },
      ]
      if (!this.contractData.contract_approval_id) {
        this.guardDatas.map(guad => {
          const r = res.find(it => it.type && it.type === +guad.gua_method)
          if (r) {
            r.num++
            r.value = true
          }
        })
        res[6].value = this.guardDatas.length === 0
      } else {
        res.map(item => {
          item.num = this.contractData[item.key]
          item.value = +item.num > 0
          return item
        })
        res[6].value = !res.some((item, index) => +item.num > 0 && index > 0 && index < 6)
      }

      this.$emit('get-type', { type: 'busContracts', data: res })
      return res
    },
    // 保证合同字符串拼接
    getGuadGuarantee(data) {
      return `${data.gua_entity} 向 ${this.relatedData.customer_name || ''} 自愿承担连带责任。`
    },
    // 质押合同字符串拼接
    getGuadPledge(data) {
      return `${data.gua_entity_corp || ''} 所持有 ${data.gua_entity || ''} ${
        data.pledge_equity || '-'
      }% 股权，价值 ${data.pledge_funds_cur || ''} 万元，提供质押反担保，办理股权出质登记。`
    },
    // 抵押合同字符串拼接
    getGuadMortgage(data) {
      return `${data.gua_entity} 用 ${data.gua_list_des || ''} 做抵押。`
    },
  },
}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
